package com.kun.demo.action;


import com.kun.demo.service.IModifyService;
import com.kun.demo.service.IQueryService;
import com.kun.spring.framework.annotation.FKAutowired;
import com.kun.spring.framework.annotation.FKController;
import com.kun.spring.framework.annotation.FKRequestMapping;
import com.kun.spring.framework.annotation.FKRequestParam;
import com.kun.spring.framework.webmvc.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 公布接口url
 * @author Tom
 *
 */
@FKController
@FKRequestMapping("/web")
public class MyAction {

	@FKAutowired
	IQueryService queryService;
	@FKAutowired
	IModifyService modifyService;

	@FKRequestMapping("/query.json")
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response,
							  @FKRequestParam("name") String name){
		String result = queryService.query(name);
		return out(response,result);
	}
	
	@FKRequestMapping("/add*.json")
	public ModelAndView add(HttpServletRequest request,HttpServletResponse response,
			   @FKRequestParam("name") String name,@FKRequestParam("addr") String addr){
		try {
			String result = modifyService.add(name, addr);
			return out(response,result);
		}catch (Throwable e){
			Map<String,String> model = new HashMap<String,String>();
			model.put("detail",e.getCause().getMessage());
			model.put("stackTrace", Arrays.toString(e.getStackTrace()));
			return new ModelAndView("500",model);
		}
	}
	
	@FKRequestMapping("/remove.json")
	public ModelAndView remove(HttpServletRequest request, HttpServletResponse response,
								 @FKRequestParam("id") Integer id){
		String result = modifyService.remove(id);
		return out(response,result);
	}
	
	@FKRequestMapping("/edit.json")
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response,
			@FKRequestParam("id") Integer id,
			@FKRequestParam("name") String name){
		String result = modifyService.edit(id,name);
		return out(response,result);
	}
	
	
	
	private ModelAndView out(HttpServletResponse resp,String str){
		try {
			resp.getWriter().write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
